package com.ruoyi.project.cms.role.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.cms.role.domain.SysRole;
import com.ruoyi.project.cms.role.mapper.SysRoleMapper;
import com.ruoyi.project.cms.role.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 公司:
 * 作者:胖虎
 * 类名:SysRoleServiceImpl
 * 描述:
 * 时间:2020-05-19
 */

@Service
public class SysRoleServiceImpl   implements SysRoleService {

    @Autowired
    private SysRoleMapper  sysRoleMapper;

    @Override
    public   List<SysRole>   selectRoleList(SysRole role) {
        return     sysRoleMapper.getByAll(role);
    }

    @Override
    public    String   checkRoleNameUnique(SysRole  role) {
        SysRole info = sysRoleMapper.checkRoleNameUnique(role.getRoleName());
        if(StringUtils.isNotNull(info)){
              return UserConstants.ROLE_NAME_NOT_UNIQUE;
        }
        return   UserConstants.ROLE_NAME_UNIQUE;

    }


    /**
     * 角色的添加
     * @param role
     * @return
     */
    @Override
    public int insertRole(SysRole role) {

        role.setCreateBy(ShiroUtils.getLoginName());
        //新增角色信息
        Long  rid = sysRoleMapper.insertRole(role);
        role.setRoleId(rid);
        return   insertRoleMenu(role);
    }


    /**
     * 角色状态的调整
     * @param role
     * @return
     */
    @Override
    public int changeStatus(SysRole role) {
        return sysRoleMapper.changeStatus(role);
    }


    /**
     * 橘色的删除
     * @param ids
     * @return
     */
    @Override
    public int deleteRoleByIds(String ids) {

        Long[] roleIds = Convert.toLongArray(ids);
        return   sysRoleMapper.deleteRoleByIds(roleIds);
    }


    /**
     * 添加角色同时添加权限
     * @param role
     * @return
     */
    private   int   insertRoleMenu(SysRole role) {

        int  rows=-1;
        try {
            Long  rid=role.getRoleId();
            for(Long  mid:role.getMenuIds()){
                sysRoleMapper.insertMenu( rid, mid);

            }
            return  6;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  rows;
    }
}
